package com.pengchuang.ACS.face.controller;

import java.util.Arrays;
import java.util.Map;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pengchuang.ACS.common.utils.ResultCode;
import com.pengchuang.ACS.face.entity.CellEntity;
import com.pengchuang.ACS.face.service.CellService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.pengchuang.ACS.face.entity.DoorEntity;
import com.pengchuang.ACS.face.service.DoorService;
import com.pengchuang.ACS.common.utils.PageUtils;
import com.pengchuang.ACS.common.utils.R;

import javax.servlet.http.HttpServletRequest;


/**
 * 
 *
 * @author pengchaung
 * @email pengshi12138@outlook.com
 * @date 2023-03-16 21:25:07
 */
@RestController
@RequestMapping("face/door")
public class DoorController {
    @Autowired
    private DoorService doorService;

    @Autowired
    private CellService cellService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){

        PageUtils page = doorService.queryPage(params);

        return R.ok().put("result", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id){
		DoorEntity door = doorService.getById(id);

        return R.ok().put("result", door);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody DoorEntity door){
        if (door.getId() == null) {
            // 生成授权码
            door.setAuthCode(UUID.fastUUID().toString());
        }
        // 判断是否存在对应的 cell
        CellEntity cell = cellService.getBaseMapper().selectOne(
                new QueryWrapper<CellEntity>().eq("cell_name", door.getCellName()));
        if (cell == null) {
            return R.error(ResultCode.PARAM_VALID_FAIL);
        }
        door.setCellId(cell.getId());
        doorService.saveOrUpdate(door);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestParam Integer[] ids){
		doorService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/is_open")
    public R open(@RequestParam Integer id, @RequestParam Integer isOpen){
        if (isOpen != 0 && isOpen != 1) {
            return R.error(ResultCode.PARAM_VALID_FAIL);
        }
        DoorEntity doorEntity = doorService.getById(id);
        doorEntity.setIsOpen(isOpen);
        doorService.updateById(doorEntity);
        return R.ok();
    }

}
